﻿using System.Collections;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace etcetera.Mvc.UI
{
    /// <summary>
    /// Writes the passed data source as an Excel file to the HttpResponse.
    /// http://www.highoncoding.com/Articles/566_JQuery_jqGrid_Export_to_Excel_Using_ASP_NET_MVC_Framework.aspx
    /// </summary>
    public static class ExcelExport
    {
        public static void Do(HttpResponseBase httpResponse, IEnumerable dataSource, string fileName)
        {
            httpResponse.ClearContent();
            httpResponse.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName));

            httpResponse.ContentType = "application/excel";

            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            var gridView = new GridView();
            gridView.DataSource = dataSource;
            gridView.DataBind();
            gridView.RenderControl(htw);

            httpResponse.Write(sw.ToString());
            httpResponse.End();
        }
    }
}
